# -*- coding: utf-8 -*-
import pendulum
from datetime import timedelta
from spmi.time_sensor.time_after_05_30 import time_after_05_30
from utils.operators.cluster_for_spark_sql_operator import SparkSqlOperator
from airflow.exceptions import AirflowSkipException

cst = pendulum.timezone('Asia/Shanghai')

class FinanceDemandSqlSensor(SparkSqlOperator):

    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        schedule_date = ['16']

        if day.strftime('%d') not in schedule_date:
            print(f'{day.strftime("%d")} not in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%d")} in {schedule_date}, run now')
            super().pre_execute(context)

spmi_dm__dm_finance_demand_excel = FinanceDemandSqlSensor(
    task_id='spmi_dm__dm_finance_demand_excel',
    task_concurrency=1,
    pool_slots=1,
    master='yarn',
    name='spmi_dm__dm_finance_demand_excel_{{ execution_date | date_add(1) | cst_ds }}',
    sql='spmi/dm/spmi/dm_finance_demand_excel/execute.sql',
    retries=1,
    driver_memory='4G',
    driver_cores=2,
    executor_cores=4,
    executor_memory='16G',
    email=['yushuo@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    num_executors=40,  # spark.dynamicAllocation.enabled 为 True 时，num_executors 表示最少 Executor 数
    conf={'spark.dynamicAllocation.enabled': 'true',  # 动态资源开启
          'spark.shuffle.service.enabled': 'true',  # 动态资源 Shuffle 服务开启
          'spark.dynamicAllocation.maxExecutors': 60,  # 动态资源最大扩容 Executor 数
          'spark.dynamicAllocation.cachedExecutorIdleTimeout': 300,  # 动态资源自动释放闲置 Executor 的超时时间(s)
          'spark.sql.sources.partitionOverwriteMode': 'dynamic',  # 允许删改已存在的分区
          'spark.sql.shuffle.partitions': 800,
          'spark.shuffle.consolidateFiles': 'true',
          'spark.executor.memoryOverhead': '2G',  # 堆外内存

          },
    # hiveconf={'hive.exec.dynamic.partition': 'true',  # 动态分区
    #           'hive.exec.dynamic.partition.mode': 'nonstrict',
    #           'hive.exec.max.dynamic.partitions': 200,  # 每天生成 20 个分区
    #           'hive.exec.max.dynamic.partitions.pernode': 200,  # 每天生成 20 个分区
    #           },
    yarn_queue='pro',
    execution_timeout=timedelta(hours=2),
)

spmi_dm__dm_finance_demand_excel <<[
    time_after_05_30
]
